package com.yuanli.modules.system.controller;

import cn.hutool.core.util.RandomUtil;
import com.yuanli.common.api.CommonAPI;
import com.yuanli.common.api.vo.Result;
import com.yuanli.common.constant.CacheConstant;
import com.yuanli.common.constant.CommonConstant;
import com.yuanli.common.system.vo.LoginUser;
import com.yuanli.common.utils.*;
import com.yuanli.modules.log.service.BaseCommonService;
import com.yuanli.modules.system.entity.SysUser;
import com.yuanli.modules.system.model.LoginModel;
import com.yuanli.modules.system.service.ISysDictService;
import com.yuanli.modules.system.service.ISysPermissionService;
import com.yuanli.modules.system.service.ISysUserService;
import com.yuanli.modules.system.vo.LoginUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 登录 前端控制器
 * </p>
 */
@Slf4j
@RequestMapping("/sys")
@RestController
@Api(tags = "用户登录")
public class LoginController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private CommonAPI sysBaseApi;

    @Resource
    private BaseCommonService baseCommonService;
    @Autowired
    private ISysPermissionService sysPermissionService;


    /**
     * 为了直接访问后端打开有数据
     */
    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Result<LoginUserVo> login(@RequestBody LoginModel loginModel) {
        Result<LoginUserVo> result = new Result<LoginUserVo>();
        String username = loginModel.getUsername();
        String password = loginModel.getPassword();
        String captcha = loginModel.getCode();
        if (captcha == null) {
            result.error500("验证码无效");
            return result;
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        // 加入密钥作为混淆，避免简单的拼接，被外部利用
        String origin = lowerCaseCaptcha + loginModel.getCodeKey() + CommonUtils.signatureSecret;
        String realKey = Md5Util.md5Encode(origin, "utf-8");

        Object checkCode = redisUtil.get(realKey);
        if (checkCode == null || !checkCode.toString().equals(lowerCaseCaptcha)) {
            log.warn("验证码错误，key= {} , Ui checkCode= {}, Redis checkCode = {}", loginModel.getCodeKey(), lowerCaseCaptcha, checkCode);
            result.error500("验证码错误");
            // 改成特殊的code 便于前端判断
            result.setCode(HttpStatus.PRECONDITION_FAILED.value());
            return result;
        }
        //1. 校验用户是否有效
        SysUser sysUser = sysUserService.getUserByName(username);
        result = sysUserService.checkUserIsEffective(sysUser);
        if (!result.isSuccess()) {
            return result;
        }
        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
        String syspassword = sysUser.getPassword();
        if (!syspassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }
        userInfo(sysUser, result);
        // 登录成功，删除redis中的验证码
        redisUtil.del(realKey);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUser, loginUser);
        baseCommonService.addLog("用户名: " + username + ",登录成功！", CommonConstant.LOG_TYPE_1, null, loginUser);
        return result;
    }

    /**
     * 后台生成图形验证码 ：有效
     *
     * @param response
     * @param key
     */
    @ApiOperation("获取验证码")
    @GetMapping(value = "/randomImage/{key}")
    public Result<String> randomImage(HttpServletResponse response, @PathVariable("key") String key) {
        Result<String> res = new Result<String>();
        try {
            //生成验证码
            String code = RandomUtil.randomString("qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890", 4);
            //存到redis中
            String lowerCaseCode = code.toLowerCase();

            // 加入密钥作为混淆，避免简单的拼接，被外部利用
            String origin = lowerCaseCode + key + CommonUtils.signatureSecret;
            String realKey = Md5Util.md5Encode(origin, "utf-8");

            redisUtil.set(realKey, lowerCaseCode, 60);
            log.info("获取验证码， nor key = {}，Redis key = {}，checkCode = {}", key, realKey, code);
            //返回前端
            String base64 = RandImageUtil.generate(code);
            res.setSuccess(true);
            res.setResult(base64);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            res.error500("获取验证码失败,请检查redis配置!");
            return res;
        }
        return res;
    }

    /**
     * 用户信息
     *
     * @param sysUser
     * @param result
     * @return
     */
    private Result<LoginUserVo> userInfo(SysUser sysUser, Result<LoginUserVo> result) {
        String username = sysUser.getUsername();
        String syspassword = sysUser.getPassword();

        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUserInfo(sysUser);
        loginUserVo.setToken(token);
        loginUserVo.setSysAllDictItems(sysDictService.queryAllDictItems());
        loginUserVo.setAuths(sysPermissionService.ferAuthData(username));
        result.setResult(loginUserVo);
        result.success("登录成功");
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.set(CommonConstant.Login_User_Vo + token, loginUserVo.getAuths());
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        redisUtil.expire(CommonConstant.Login_User_Vo + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        return result;
    }

    /**
     * 退出登录
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/logout")
    public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        //用户退出逻辑
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (oConvertUtils.isEmpty(token)) {
            return Result.error("退出登录失败！");
        }
        String username = JwtUtil.getUsername(token);
        LoginUser sysUser = sysBaseApi.getUserByName(username);
        if (sysUser != null) {
            log.info(" 用户名:  " + sysUser.getRealname() + ",退出成功！ ");
            //清空用户登录Token缓存
            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
            //清空用户登录Shiro权限缓存
            redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
            //清空用户的缓存信息（包括部门信息），例如sys:cache:user::<username>
            redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
            //调用shiro的logout
            SecurityUtils.getSubject().logout();
            return Result.ok("退出登录成功！");
        } else {
            return Result.error("Token无效!");
        }
    }
}
